package com.zh.yqbj.config;

import com.zh.yqbj.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {
    @Value("${spring.servlet.multipart.location}")
    private String basePath;
    @Value("${file.mapping-location}")
    private String mappingPath;

    /**
     * springboot提供了CorsWebFilter进行跨域
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 配置跨域
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许哪个请求头
        corsConfiguration.addAllowedHeader("*");
        // 允许哪个方法进行跨域
        corsConfiguration.addAllowedMethod("*");
        // 允许哪个请求来源进行跨域
        // corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOriginPattern("*");
        // 是否允许携带cookie进行跨域
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", corsConfiguration);
        log.info("解决跨域");
        return new CorsWebFilter(source);
    }

    /**
     * 扩展mvc框架消息转换器
     * @param converters List<HttpMessageConverter<?>>
     */
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters){
        log.info("创建时间格式转换器...");
        //创建一个消息转换器
        MappingJackson2HttpMessageConverter converter =new MappingJackson2HttpMessageConverter();
        //为消息转换器创建一个对象转换器
        converter.setObjectMapper(new JacksonObjectMapper());
        //添加自定义消息转换器 到 转换器容器首位
        converters.add(0,converter);
    }

    /**
     * 本地文件映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("文件路径映射:{}->{}",basePath,mappingPath);
        registry.addResourceHandler(mappingPath).addResourceLocations("file:" + basePath);
    }
}
